package com.lyw.contianer;

import com.lyw.exception.GlobalException;
import com.lyw.utils.StringUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class GlobalContext {

    private static final Map<String, Object> container = new ConcurrentHashMap<>(50);

    private GlobalContext() {
        init();
    }

    private void init() {
        System.out.println("init is run ......");
    }


    public void setBean(Object o) {

        if (o == null) {
            throw new GlobalException(StringUtil.format("当前放入容器的对象不能为空！"));
        }

        container.put(o.getClass().getName(), o);
    }

    public Object getBean(Class<?> clazz) {
        if (container.isEmpty()) {
            throw new GlobalException(StringUtil.format("当前容器为空！"));
        }

        if (clazz == null) {
            throw new GlobalException(StringUtil.format("需要在容器中获取的 class 不能为空！"));
        }

        Object o = container.get(clazz.getName());
        if (o == null) {
            throw new GlobalException(StringUtil.format("当前容器中无法获取到 {} 的信息！", clazz.getName()));
        }

        return o;
    }
}
